package com.topcent.tioxyc.controller;

import lombok.Getter;
import lombok.Setter;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @author: 陈百万
 * @date: 2025/3/11 11:46
 * @Description: 测试img
 */
@RestController
public class OpenCVMatting {
    /**
     * 将指定图片背景透明化处理
     *
     * @param inputPath      原始图片路径
     * @param outputPath     输出图片路径
     * @param colorThreshold 背景色阈值(0-255)
     */
    public static String makeBackgroundTransparent(String inputPath, String outputPath, int colorThreshold) throws IOException {
        // 读取原始图片
        BufferedImage sourceImage = ImageIO.read(new File(inputPath));

        // 创建支持透明通道的缓冲区图像
        BufferedImage transparentImage = new BufferedImage(
                sourceImage.getWidth(),
                sourceImage.getHeight(),
                BufferedImage.TYPE_INT_ARGB
        );

        // 图像绘制与处理
        Graphics2D graphics = transparentImage.createGraphics();
        graphics.drawImage(sourceImage, 0, 0, null);

        // 像素级透明处理
        processPixels(transparentImage, colorThreshold);

        // 优化边缘抗锯齿
        graphics.setRenderingHint(
                RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON
        );
        graphics.dispose();

        // 保存处理结果
        ImageIO.write(transparentImage, "PNG", new File(outputPath));
        return outputPath;
    }

    private static void processPixels(BufferedImage image, int threshold) {
        int width = image.getWidth();
        int height = image.getHeight();

        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int pixel = image.getRGB(x, y);

                // 分解颜色通道
                int alpha = (pixel >> 24) & 0xff;
                int red = (pixel >> 16) & 0xff;
                int green = (pixel >> 8) & 0xff;
                int blue = pixel & 0xff;

                // 智能背景检测逻辑
                if (isBackground(red, green, blue, threshold)) {
                    pixel = (0 << 24) | (red << 16) | (green << 8) | blue; // Alpha设为0
                } else {
                    pixel = (255 << 24) | (red << 16) | (green << 8) | blue; // Alpha设为255
                }

                image.setRGB(x, y, pixel);
            }
        }
    }

    // 背景色判断算法（可扩展）
    private static boolean isBackground(int r, int g, int b, int threshold) {
        // 白色背景检测逻辑（可修改为其他颜色判断）
        return r >= threshold && g >= threshold && b >= threshold;
    }

    // 本地测试专用接口
    @PostMapping("/local-test")
    public String localTest(@RequestBody TestRequest request) throws IOException {
        // 1. 读取本地图片
        BufferedImage source = ImageIO.read(new File(request.getImagePath()));

        // 2. 加载图标 (建议将图标文件放在项目根目录)
        String iconPath = request.isApproved() ? makeBackgroundTransparent("D:\\img\\111.jpg", "D:\\img\\222.jpg", 230) : "D:\\img\\天空001.png";
        BufferedImage icon = ImageIO.read(new File(iconPath));

        // 比例缩放计算
        int originalWidth = icon.getWidth();
        int originalHeight = icon.getHeight();
        float scaleRatio = Math.min(
                (source.getWidth() * 0.2f) / originalWidth,
                (source.getHeight() * 0.2f) / originalHeight
        );
        int scaledWidth = (int) (originalWidth * scaleRatio);
        int scaledHeight = (int) (originalHeight * scaleRatio);

        // 高质量缩放
        BufferedImage scaledIcon = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = scaledIcon.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g2d.drawImage(icon, 0, 0, scaledWidth, scaledHeight, null);
        g2d.dispose();

        // 左上角定位
        int margin = 20;
        int x = margin;
        int y = margin;

        // 边界检测
        if (x + scaledWidth > source.getWidth() || y + scaledHeight > source.getHeight()) {
            throw new IllegalArgumentException("Logo尺寸超出画布范围");
        }

        Graphics2D graphics = source.createGraphics();

        // 设置透明度混合（参考网页2的AlphaComposite用法）
        graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.9f));

        // 绘制缩放后的图标（网页2中的drawImage方法扩展）
        graphics.drawImage(scaledIcon,
                x,
                y,
                scaledWidth,
                scaledHeight,
                null);

        graphics.dispose();

        graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);

        // 确保右下角坐标不超过原图范围（网页1的边界检查思路）
        assert x + scaledWidth <= source.getWidth();
        assert y + scaledHeight <= source.getHeight();
        // 临时绘制定位框
        graphics.setColor(Color.RED);
        graphics.drawRect(x, y, scaledWidth, scaledHeight);

        // 4. 保存结果到本地
        String outputPath = "D:/img/processed_" + System.currentTimeMillis() + ".jpg";
        ImageIO.write(source, "jpg", new File(outputPath));

        return "处理完成！文件保存至：" + outputPath;
    }

    // 测试请求参数类
    @Setter
    @Getter
    static class TestRequest {
        private String imagePath;
        private boolean approved;
    }
}
